﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace CommonLib.OfficeReport
{
    public class DLLWrapper
    {
        /// <summary> 

        /// 原型是 :HMODULE LoadLibrary(LPCTSTR lpFileName); 

        /// </summary> 

        /// <param name="lpFileName">DLL 文件名 </param> 

        /// <returns> 函数库模块的句柄 </returns> 

        [DllImport("kernel32.dll")]

        public static extern IntPtr LoadLibrary(string lpFileName);

        /// <summary> 

        /// 原型是 : FARPROC GetProcAddress(HMODULE hModule, LPCWSTR lpProcName); 

        /// </summary> 

        /// <param name="hModule"> 包含需调用函数的函数库模块的句柄 </param> 

        /// <param name="lpProcName"> 调用函数的名称 </param> 

        /// <returns> 函数指针 </returns> 

        [DllImport("kernel32.dll")]

        public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);

        /// <summary> 

        /// 原型是 : BOOL FreeLibrary(HMODULE hModule); 

        /// </summary> 

        /// <param name="hModule"> 需释放的函数库模块的句柄 </param> 

        /// <returns> 是否已释放指定的 Dll</returns> 

        [DllImport("kernel32", EntryPoint = "FreeLibrary", SetLastError = true)]

        public static extern bool FreeLibrary(IntPtr hModule);

        ///<summary>
        ///通过非托管函数名转换为对应的委托, by jingzhongrong
        ///</summary>
        ///<param name="dllModule">通过LoadLibrary获得的DLL句柄</param>
        ///<param name="functionName">非托管函数名</param>
        ///<param name="t">对应的委托类型</param>
        ///<returns>委托实例，可强制转换为适当的委托类型</returns>
        public static Delegate GetFunctionAddress(IntPtr dllModule, string functionName, Type t)
        {
            IntPtr address = GetProcAddress(dllModule, functionName);
            if ((int)address == 0)
                return null;
            else
                return Marshal.GetDelegateForFunctionPointer(address, t);
        }

        ///<summary>
        ///将表示函数地址的IntPtr实例转换成对应的委托, by jingzhongrong
        ///</summary>
        public static Delegate GetDelegateFromIntPtr(IntPtr address, Type t)
        {
            if (address == IntPtr.Zero)
                return null;
            else
                return Marshal.GetDelegateForFunctionPointer(address, t);
        }

        ///<summary>
        ///将表示函数地址的int转换成对应的委托，by jingzhongrong
        ///</summary>
        public static Delegate GetDelegateFromIntPtr(int address, Type t)
        {
            if (address == 0)
                return null;
            else
                return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
        }
    }

}
